﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.Product.Bll;

namespace CIT.WMS.Product
{
    public partial class FrmProductOut : Form
    {
        public FrmProductOut()
        {
            InitializeComponent();
        }
        DataTable DtOut;
        DataTable _RecomDt;

        string realLocationSN;
        string recomLocationSN;
        string recomPartNumber;
        string realPartNumber;
        //bool isLast;

        int maxQty;

        string _BillType = "";

        private void FrmProductOut_Load(object sender, EventArgs e)
        {
            //BindCMB();

        }

        //public void BindCMB()
        //{

        //    DtOut = Bll_ProductOut.GetOutStockList();
        //    cmb_Doc.Text = "";
        //    //cmb_Doc.Items.Clear();
        //    //if (DtOut.Rows.Count > 0)
        //    //{
        //    //    foreach (DataRow dr in DtOut.Rows)
        //    //    {
        //    //        cmb_Doc.Items.Add(dr["BillNo"].ToString());
        //    //    }
        //    //}
        //}

        private void cmb_Doc_SelectedIndexChanged(object sender, EventArgs e)
        {
            InputBillNo();
        }

        public void InputBillNo()
        {
            DtOut = Bll_ProductOut.GetOutStockLists(cmb_Doc.Text);
            DataRow[] drOut = DtOut.Select(string.Format(" BillNo = '{0}'", cmb_Doc.Text));
            if (drOut.Length > 0)
            {
                var billNo = cmb_Doc.Text;
                DataTable info = Bll_ProductOut.GetOutStockInfo(cmb_Doc.Text);
                _BillType = info.Rows[0]["BillType"].ToString();

                if (info.Rows.Count > 0)
                {
                    if (string.IsNullOrEmpty(info.Rows[0]["Updator"].ToString()) || Utils.uContext.UserNamek__BackingField.Equals(info.Rows[0]["Updator"].ToString()))
                    {

                        lab_StorageSN.Text = info.Rows[0]["Storage_SN"].ToString();

                        _RecomDt = Utils.NMS.sqlDBService.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                        if (!(_RecomDt != null && _RecomDt.Rows.Count > 0))
                        {
                            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                            DialogResult dr = MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！是否强制出库??", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                            if (dr == DialogResult.OK)
                            {
                                _RecomDt = Bll_ProductOut.GetRecommendLocationSNQC(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                            }
                        }

                        var recRes = GetRecommend();

                        var IsEnd = false;
                        lab_msg.Text = "当前料号:" + recomPartNumber + "\r\n" + GetBillInfoMsg(billNo, out IsEnd);

                        if (!recRes && !IsEnd)
                        {
                            MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！");


                            cmb_Doc.Focus();
                            cmb_Doc.Text = "";
                            lab_Recom.Text = "";
                            txt_BoxNo.Text = "";
                            txt_LocationSN.Text = "";
                            txt_Qty.Text = "";

                        }


                    }
                    else
                    {
                        MessageBox.Show(cmb_Doc.Text + "已被" + info.Rows[0]["Updator"].ToString() + "操作，请选择其他单号!");
                        lab_StorageSN.Text = "";
                        cmb_Doc.Text = "";
                        cmb_Doc.Focus();
                    }
                }

            }
            else
            {
                lab_msg.Text = cmb_Doc.Text + "单号不正确,请输入正确的单据!";
                cmb_Doc.Focus();
                cmb_Doc.Text = "";
                lab_StorageSN.Text = "";


            }
        }

        public string GetBillInfoMsg(string billNo, out bool IsEnd)
        {
            var dt = Bll_ProductOut.GetDeliveryInfo(billNo);

            var boxCount = Bll_ProductOut.GetOutStockBoxsCount(billNo);


            var result = string.Empty;
            IsEnd = false;
            if (dt.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("已扫描箱数:" + boxCount);
                var isFinish = true;
                foreach (DataRow dr in dt.Rows)
                {
                    var planQty = 0;
                    if (!string.IsNullOrEmpty(dr["PlanQty"].ToString()))
                    {
                        planQty = Convert.ToInt32(dr["PlanQty"]);
                    }
                    var realQty = 0;
                    if (!string.IsNullOrEmpty(dr["SelectQty"].ToString()))
                    {
                        realQty = Convert.ToInt32(dr["SelectQty"]);
                    }
                    sb.AppendLine("物料号:" + dr["ProductNumber"] + ";数量:" + realQty + "/" + planQty);

                    if (planQty > realQty)
                    {
                        isFinish = false;
                    }
                }
                result = sb.ToString();
                if (isFinish)
                {
                    IsEnd = true;
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                    DialogResult dr = MessageBox.Show("出库单:" + billNo + "出库数量已经等于计划数量，是否确认完成?", "是否完成", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                    if (dr == DialogResult.OK)
                    {
                        Bll_ProductOut.OutStockFinish(billNo);

                        //var relatedBill = Bll_ProductOut.GetRelationBill(cmb_Doc.Text);
                        //if (relatedBill.StartsWith("VMI"))
                        //{
                        //    Bll_ProductOut.OutStockVMIDelivery(cmb_Doc.Text);
                        //}



                        //BindCMB();
                        lab_StorageSN.Text = "";
                        cmb_Doc.Focus();
                        cmb_Doc.Text = "";
                        txt_BoxNo.Text = "";
                        txt_LocationSN.Text = "";
                        txt_Qty.Text = "";
                    }
                }
            }
            return result;
        }

        public bool GetRecommend()
        {
            var result = false;
            if (_RecomDt != null && _RecomDt.Rows.Count > 0)
            {
                var dr = _RecomDt.Rows[0];
                recomLocationSN = dr["Location_SN"].ToString();
                recomPartNumber = dr["PartNumber"].ToString();
                try
                {
                    lab_Recom.Text = recomLocationSN.Split('#')[1] + recomLocationSN.Split('#')[2] + ":" + dr["Qty"].ToString();
                }
                catch (Exception ex)
                {
                    lab_Recom.Text = dr["Storage_SN"].ToString();
                }

                txt_BoxNo.Focus();
                txt_BoxNo.Text = "";
                txt_Qty.Text = "";

                result = true;
            }
            else
            {
                recomLocationSN = string.Empty;
                recomPartNumber = string.Empty;

                cmb_Doc.Focus();
                cmb_Doc.Text = "";
                lab_Recom.Text = "";
                txt_BoxNo.Text = "";
                txt_LocationSN.Text = "";
                txt_Qty.Text = "";

            }

            return result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (cmb_Doc.Text == null || cmb_Doc.Text.ToString() == "")
            {
                //lab_msg.Text = "请先选择单据";
                MessageBox.Show("请先选择单据");
                return;
            }
            _RecomDt = Utils.NMS.sqlDBService.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
            if (!(_RecomDt != null && _RecomDt.Rows.Count > 0))
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！是否强制出库??", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                if (dr == DialogResult.OK)
                {
                    _RecomDt = Bll_ProductOut.GetRecommendLocationSNQC(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                }
            }

            GetRecommend();

            var IsEnd = false;
            lab_msg.Text = GetBillInfoMsg(cmb_Doc.Text, out IsEnd);
        }

        private void txt_BoxNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }
            if (string.IsNullOrEmpty(cmb_Doc.Text))
            {
                MessageBox.Show("请选择单号!");
                cmb_Doc.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }
            if (_RecomDt.Rows.Count == 0)
            {
                MessageBox.Show("库存不足，" + cmb_Doc.Text + "无法推荐库位！");
                return;
            }

            var splitList = txt_BoxNo.Text.Split('-');
            var boxNo = splitList.FirstOrDefault();
            txt_BoxNo.Text = boxNo;

            DataTable dateHoldBox = Bll_ProductOut.GetHoldBox(txt_BoxNo.Text);
            if (dateHoldBox != null && dateHoldBox.Rows.Count > 0)
            {
                MessageBox.Show("该箱号:" + txt_BoxNo.Text + "已冻结，不能出库！");
                return;
            }


            var isExit = Bll_ProductOut.IsExitBill(cmb_Doc.Text, txt_BoxNo.Text);
            if (isExit)
            {
                MessageBox.Show(txt_BoxNo.Text + "已扫描!");
                txt_BoxNo.Text = "";
                return;
            }


            DataTable dtBox = Bll_ProductOut.GetBoxNoInfo(txt_BoxNo.Text);

            realPartNumber = _RecomDt.Rows[0]["PartNumber"].ToString();

            if (dtBox == null || dtBox.Rows.Count == 0)
            {
                if (splitList.Count() > 1)
                {
                    try
                    {
                        maxQty = Convert.ToInt32(splitList.LastOrDefault());
                    }
                    catch
                    {
                        maxQty = 0;
                    }
                }
                else
                {
                    maxQty = 0;
                }
                MessageBox.Show("系统无" + txt_BoxNo.Text + "箱号信息，请确认此箱物料号与出库单中物料号一致！");
            }
            else
            {
                var realQty_Box = 0;

                if (!string.IsNullOrEmpty(dtBox.Rows[0]["RealQty"].ToString()))
                {
                    realQty_Box = Convert.ToInt32(dtBox.Rows[0]["RealQty"]);
                }

                if (dtBox.Rows[0]["Status"].ToString().Equals("1") || realQty_Box == 0)
                {
                    MessageBox.Show(txt_BoxNo.Text + "已被使用，请选择其他箱！");
                    return;
                }

                maxQty = realQty_Box;

                if (!realPartNumber.Equals(dtBox.Rows[0]["PartNumber"].ToString()))
                {
                    MessageBox.Show(txt_BoxNo.Text + "箱号物料号不对，请重新扫描！");
                    txt_BoxNo.Text = "";
                    txt_BoxNo.Focus();
                    return;
                }
            }

            if (maxQty == 0)
            {
                txt_Qty.Text = string.Empty;
            }
            else
            {
                txt_Qty.Text = maxQty.ToString();
            }

            txt_Qty.Focus();

        }

        public bool CheckBillNoProNumIsFinish(string billNo, string productNumber, int qty, out int diff)
        {
            var dt = Bll_ProductOut.GetDeliveryInfo(billNo);

            var isFinish = true;
            diff = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (productNumber.Equals(dr["ProductNumber"].ToString()))
                {
                    var planQty = 0;
                    if (!string.IsNullOrEmpty(dr["PlanQty"].ToString()))
                    {
                        planQty = Convert.ToInt32(dr["PlanQty"]);
                    }
                    var realQty = 0;
                    if (!string.IsNullOrEmpty(dr["SelectQty"].ToString()))
                    {
                        realQty = Convert.ToInt32(dr["SelectQty"]);
                    }
                    diff = planQty - realQty;
                    realQty = realQty + qty;
                    if (planQty > realQty)
                    {
                        isFinish = false;
                    }
                    break;
                }

            }
            return isFinish;
        }

        private void cmb_Doc_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                InputBillNo();
            }
        }

        private void txt_LocationSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }

            var splitList = txt_BoxNo.Text.Split('-');
            var boxNo = splitList.FirstOrDefault();
            txt_BoxNo.Text = boxNo;

            if (_BillType.Contains("返工出库单") == false)
            {
                DataTable dateHoldBox = Bll_ProductOut.GetHoldBox(txt_BoxNo.Text);
                if (dateHoldBox != null && dateHoldBox.Rows.Count > 0)
                {
                    MessageBox.Show("该箱号:" + txt_BoxNo.Text + "已冻结，不能出库！");
                    return;
                }
            }

            var isExit = Bll_ProductOut.IsExitBill(cmb_Doc.Text, txt_BoxNo.Text);
            if (isExit)
            {
                MessageBox.Show(txt_BoxNo.Text + "已扫描!");
                return;
            }


            if (string.IsNullOrEmpty(txt_Qty.Text))
            {
                //lab_msg.Text = "请输入出库成品数量!";
                MessageBox.Show("请输入出库成品数量!");
                return;
            }

            var boxnumDt = Bll_ProductOut.GetBoxNum(txt_BoxNo.Text);

            var BoolBN = false;

            if (boxnumDt != null && boxnumDt.Rows.Count > 0)
            {
                var PutawayQty = Convert.ToInt32(boxnumDt.Rows[0]["PutawayQty"]);
                if (PutawayQty < Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text)))
                {
                    BoolBN = true;
                }
            }
            if (BoolBN)
            {
                MessageBox.Show("该箱号" + txt_BoxNo.Text + "输入的数量超过实际的数量！");
                return;
            }

            if (string.IsNullOrEmpty(realPartNumber))
            {
                MessageBox.Show("请先输入箱号并回车！");
                txt_BoxNo.Focus();
                return;
            }

            if (txt_LocationSN.Text.Contains("#"))
            {
                realLocationSN = txt_LocationSN.Text;
            }


            var arry = realLocationSN.Split('#');
            if (arry.Count() < 3)
            {
                MessageBox.Show("输入的库位格式不正确，请重新输入！");
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }
            txt_LocationSN.Text = arry[1] + arry[2];

            //扫描库位与推荐库位不一致todo
            //if (lab_Recom.Text.StartsWith(txt_LocationSN.Text) == false)
            //{
            //    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

            //    DialogResult dr = MessageBox.Show("出库单库位:" + txt_LocationSN.Text + "与推荐库位" + lab_Recom.Text + "不一致，请检查", "消息提示", messButton, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

            //    if (dr == DialogResult.Cancel)
            //    {
            //        return;
            //    }
            //}

            var status = Bll_ProductOut.GetLocationSNStatusInInventory(realLocationSN);
            if (status == 0)
            {
                var str = txt_LocationSN.Text + "库存不足，请点击重新推荐按钮，选择其他推荐库位！";

                MessageBox.Show(str);
                txt_LocationSN.Text = "";
                txt_LocationSN.Focus();
                return;
            }

            var qty = Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text));
            var locationSNQty = Convert.ToInt32(_RecomDt.Rows[0]["Qty"]);
            if (qty == 0)
            {
                //lab_msg.Text = "出库成品数量不能为0或者为空!";
                MessageBox.Show("出库成品数不能为0或者为空!");
                return;
            }

            //if (!isLast)
            //{
            //    if (qty > locationSNQty)
            //    {
            //        MessageBox.Show("出库成品数" + qty + "不能大于库位成品数" + locationSNQty + "!");
            //        return;
            //    }
            //}
            if (_BillType != "返工出库单")
            {
                var dtInver = Bll_ProductIn.GetInventoryInfo(realLocationSN, realPartNumber);
                string extInver = string.Empty;
                if (dtInver != null && dtInver.Rows.Count > 0)
                {
                    extInver = dtInver.Rows[0]["Ext1"].ToString();
                }
                bool isPD = false;
                if (string.IsNullOrEmpty(extInver) || extInver.Length != 8)
                {
                    isPD = true;
                }
                else
                {
                    try
                    {
                        DateTime ditetimeExt = Convert.ToDateTime(extInver.Substring(0, 4) + "-" + extInver.Substring(4, 2) + "-" + extInver.Substring(6, 2));
                        if (ditetimeExt >= DateTime.Now)
                        {
                            isPD = false;
                        }
                    }
                    catch
                    {
                        MessageBox.Show("该库位有效期不是正确的日期格式!");
                        return;
                    }
                }
                if (isPD)
                {
                    var dtLiftTime = Bll_ProductOut.GetExpriTime(realPartNumber, realLocationSN);
                    if (!(dtLiftTime != null && dtLiftTime.Rows.Count > 0))
                    {
                        //MessageBoxButtons messButtons = MessageBoxButtons.OKCancel;

                        //DialogResult drs = MessageBox.Show("该物料有效期已过，无法出库!!是否强制出库!", "出库确认", messButtons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                        //if (drs == DialogResult.Cancel)
                        //{
                        //    //MessageBox.Show("该物料有效期已过，无法出库!!");
                        //    return;
                        //}

                        MessageBox.Show("该物料有效期已过，无法出库!!");
                        return;
                    }
                }
            }

            var isCanAddQty = Bll_ProductOut.OutStockIsCanAddQty(cmb_Doc.Text, realPartNumber, qty);

            if (!isCanAddQty)
            {
                MessageBox.Show("物料号" + realPartNumber + "的出库数量" + qty + "不能大于计划数量!");
                txt_Qty.Text = "";
                return;
            }

            //bool isTrue = Bll_ProductOut.ProductOutStock(cmb_Doc.Text, txt_BoxNo.Text, qty, realLocationSN, realPartNumber);
            bool isTrue = Utils.NMS.sqlDBService.ProductOutStock(cmb_Doc.Text, txt_BoxNo.Text, qty, realLocationSN, realPartNumber, Utils.uContext.UserNamek__BackingField);
            if (isTrue)
            {
                //_RecomDt = Bll_ProductOut.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                _RecomDt = Utils.NMS.sqlDBService.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, cmb_Doc.Text);
                var Isend = false;
                lab_msg.Text = txt_BoxNo.Text + "出库成功！\r\n" + "当前料号:" + recomPartNumber + "\r\n" + GetBillInfoMsg(cmb_Doc.Text, out Isend);
                //MessageBox.Show(txt_BoxNo.Text + "出库成功！/n" + GetBillInfoMsg(cmb_Doc.Text));
                GetRecommend();

            }
            else
            {
                //lab_msg.Text = txt_BoxNo.Text + "出库失败!";
                MessageBox.Show(txt_BoxNo.Text + "出库失败，请检查箱号与库位是否一致,或此库位是否有足够的成品！");
                txt_BoxNo.Focus();
                txt_BoxNo.Text = "";
                txt_Qty.Text = "";
                txt_LocationSN.Text = "";
            }

        }

        private void txt_Qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            if (string.IsNullOrEmpty(txt_BoxNo.Text))
            {
                MessageBox.Show("箱号不能为空!");
                return;
            }

            if (string.IsNullOrEmpty(txt_Qty.Text))
            {
                //lab_msg.Text = "请输入出库成品数量!";
                MessageBox.Show("请输入出库成品数量!");
                return;
            }

            if (string.IsNullOrEmpty(realPartNumber))
            {
                MessageBox.Show("请先输入箱号并回车！");
                txt_BoxNo.Focus();
                return;
            }

            txt_Qty.Text = txt_Qty.Text.Split('-').LastOrDefault();

            var qty = 0;

            try
            {
                qty = Convert.ToInt32(Convert.ToDecimal(txt_Qty.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("只能输入数字!");
                txt_Qty.Text = "";
                return;
            }

            var locationSNQty = Convert.ToInt32(_RecomDt.Rows[0]["Qty"]);
            if (qty == 0)
            {
                //lab_msg.Text = "出库成品数量不能为0或者为空!";
                MessageBox.Show("出库成品数量不能为0或者为空!");
                return;
            }

            //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            //DialogResult dr = MessageBox.Show("本次操作的出库数量：" + qty + ", 请确认！", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);


            //if (dr == DialogResult.OK)
            //{
            //    int diff = 0;

            //    isLast = CheckBillNoProNumIsFinish(cmb_Doc.Text, realPartNumber, qty, out diff);

            //    if (isLast)
            //    {
            //        //txt_Qty.Text = diff.ToString();
            //        if (maxQty != 0 && qty > maxQty)
            //        {
            //            MessageBox.Show("输入的成品数" + qty + "不能大于库存数" + maxQty + "!");
            //            txt_Qty.Focus();
            //            txt_Qty.Text = "";
            //            return;
            //        }

            //    }
            //    else
            //    {
            //        if (maxQty != 0 && qty != maxQty)
            //        {
            //            MessageBox.Show("输入的成品数" + qty + "需与库存数" + maxQty + "一致!");
            //            txt_Qty.Focus();
            //            txt_Qty.Text = "";
            //            return;
            //        }
            //    }

            txt_LocationSN.Focus();

        }

    }
}